<?php

// menu site
class Core_Api_Toolbar
{
    /**
     * @param string $menu
     * @param string $submenu
     * @return array with multi level
     */
    public function getItems($toolbar)
    {
        $table = Nuo::getTable('core@toolbaritem');

        $select = $table -> select() -> where('enabled=1') -> order('priority ASC') -> limit(100);

        if (!empty($toolbar))
        {
            $select -> where('toolbar=?', (string)$toolbar);
        }

        $rows = $table -> fetchAll($select) -> toArray();

        // multi level process.

        $result = array();

        //
        $map0 = array();
        $map1 = array();
        $map2 = array();

        // build menu for level 1
        foreach ($rows as $index => $row)
        {
            if ($row['parent_id'] == 0)
            {
                $result[] = self::processMenuItem($row);
                $map0[$row['item_id']] = count($result) - 1;
                unset($rows[$index]);
            }
        }

        // build menu for level 2
        foreach ($rows as $index => $row)
        {
            if (isset($map0[$row['parent_id']]))
            {
                $index0 = $map0[$row['parent_id']];
                $result[$index0]['children'][] = self::processMenuItem($row);
                $map1[$row['parent_id']] = count($result[$index0]['children']) - 1;
                unset($rows[$index]);
            }
        }

        // flattern what you need to see the problem.

        return $result;
    }

    static public function processMenuItem($row)
    {
        $data = unserialize($row['data']);

        $row['data'] = array_merge(array(
            'options' => array(),
            'route' => 'default',
            'plugin' => '',
            'uri' => '',
            'label' => '',
            'encode' => 1,
            'reset' => 0,
            'type' => 'url',
            'attribs' => array()
        ), (array)unserialize($row['data']));
        return $row;
    }

}
